package cn.qiyu5522.tk_ems.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.tk_ems.entity.*;
import cn.qiyu5522.tk_ems.entity.dto.JobDTO;
import cn.qiyu5522.tk_ems.entity.dto.QueryParamDTO;
import cn.qiyu5522.tk_ems.entity.vo.JobVO;
import cn.qiyu5522.tk_ems.mapper.*;
import cn.qiyu5522.tk_ems.result.CustomMapResult;
import cn.qiyu5522.tk_ems.result.R;
import cn.qiyu5522.tk_ems.service.JobService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Tonkey
 * @since 2023-02-20
 */
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements JobService {
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private JobcategoryMapper jobcategoryMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ResumeDeliveryRecordMapper resumeDeliveryRecordMapper;

    @Override
    public R queryJobsByCondition(QueryParamDTO<JobDTO> queryParamDTO) {
        // 岗位名称 、企业名称、企业编号、工作地点、薪水、工作类别  <---查询条件
        JobDTO condition = queryParamDTO.getCondition();
        // 分页插件
        IPage<Job> jobPage = new Page<>(queryParamDTO.getCurrentPage(), queryParamDTO.getPageSize());
        LambdaQueryWrapper<Job> jobLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<JobCategory> jobCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        if(ObjectUtil.isEmpty(condition.getCompanyId())){
//            // 获取当前登录用户的编号
//            String loginInfo = (String) StpUtil.getLoginId();
//            Long loginId = Long.valueOf(loginInfo.split("-")[0]);
//            condition.setCompanyId(loginId);
//        }
        jobLambdaQueryWrapper.like(ObjectUtil.isNotEmpty(condition.getName()), Job::getName, condition.getName())
                // 工作地点编号
                .like(ObjectUtil.isNotEmpty(condition.getWorkAddressId()), Job::getWorkAddressId, condition.getWorkAddressId())
                // 岗位名称
                .eq(ObjectUtil.isNotEmpty(condition.getName()), Job::getName, condition.getName())
                // 薪水
                .like(ObjectUtil.isNotEmpty(condition.getMonthSalary()), Job::getMonthSalary, condition.getMonthSalary())
                // 发布时间 起始--截止
                .ge(ObjectUtil.isNotEmpty(condition.getCreateTimeStart()), Job::getCreateTime, condition.getCreateTimeStart())
                .le(ObjectUtil.isNotEmpty(condition.getCreateTimeEnd()), Job::getCreateTime, condition.getCreateTimeEnd())
                // 工作类别编号
                .eq(ObjectUtil.isNotEmpty(condition.getJobCategoryId()), Job::getJobCategoryId, condition.getJobCategoryId())
                // 公司编号 --默认按着这个来查
                .eq(ObjectUtil.isNotEmpty(condition.getCompanyId()), Job::getCompanyId, condition.getCompanyId());
        baseMapper.selectPage(jobPage, jobLambdaQueryWrapper);
        // 实体类转VO
        List<JobVO> jobVOS = objectMapper.convertValue(jobPage.getRecords(), new TypeReference<List<JobVO>>() {
        });

        // 岗位名称与职位名称做映射
        List<JobCategory> jobCategories = jobcategoryMapper.selectList(null);
        jobCategories.forEach(jobCategory -> {
            jobVOS.forEach(jobVO -> {
                if (Integer.valueOf(jobVO.getName()).equals(jobCategory.getId())) {
                    jobVO.setJobName(jobCategory.getName());
                }
            });
        });

        // 将公司名称与其名称作映射
        List<Long> companyIds = jobPage.getRecords().stream().map(Job::getCompanyId).collect(Collectors.toList());
        if (companyIds.size() > 0) {
            // 查询企业表获取企业名称
            List<Company> companies = companyMapper.selectBatchIds(companyIds);
            // 获取公司名称
            companies.stream().map(company -> {
                // 中间表里根据工作编号查询出来的公司名称 作映射
                for (JobVO jobVO : jobVOS) {
                    if (jobVO.getCompanyId().equals(company.getId())) {
                        jobVO.setCompanyName(company.getName());
                    }
                }
                return company;
            });
        }
        // 检测当前用户是否已经投递过简历信息
        // 获取当前用户
        String s = ((String) StpUtil.getLoginId()).split("-")[0];
        Long loginId = Long.valueOf(s);
        User user = userMapper.selectById(loginId);
        if (ObjectUtil.isNotEmpty(user)) {
            String description = user.getDescription();
            if ("学生用户".equals(description)) {
                // 查询简历投递记录表该学生的投递记录
                LambdaQueryWrapper<ResumeDeliveryRecord> recordLambdaQueryWrapper = new LambdaQueryWrapper<>();
                recordLambdaQueryWrapper.eq(ResumeDeliveryRecord::getStudentId, loginId);
                List<ResumeDeliveryRecord> resumeDeliveryRecords = resumeDeliveryRecordMapper.selectList(recordLambdaQueryWrapper);
                if (resumeDeliveryRecords.size() != 0) {
                    // 将投递记录的岗位id、公司编号与岗位表的主键id比较后，设置一个标识变量，代表该学生已经投递过该公司的该岗位。
                    for (JobVO jobVO : jobVOS) {
                        for (ResumeDeliveryRecord resumeDeliveryRecord : resumeDeliveryRecords) {
                            if (
                                    resumeDeliveryRecord.getJobId().equals(jobVO.getId())
                                            &&
                                            resumeDeliveryRecord.getCompanyId().equals(jobVO.getCompanyId())
                            ) {
                                jobVO.setHasDelivery(1);
                                break;
                            }
                        }
                    }
                }
            }
        }
        Map<String, Object> map = CustomMapResult.packagingResult(jobVOS, queryParamDTO.getCurrentPage(), queryParamDTO.getPageSize(), jobPage.getTotal());
        return R.ok().data("jobIPage", map);
    }

    @Transactional
    @Override
    public R saveMore(List<JobDTO> jobDTOs) {
        // DTO 转实体类
        List<Job> jobs = objectMapper.convertValue(jobDTOs, new TypeReference<List<Job>>() {
        });
        // 向岗位表中插入数据
        Integer integer = baseMapper.insertBatchSomeColumn(jobs);
        return integer > 0 ? R.ok().message("添加成功") : R.error().message("添加失败");
    }

    @Override
    public R queryJobInfoById(Integer id) {
        Job job = baseMapper.selectById(id);
        return R.ok().data("jobInfo",job);
    }
}
